package com.woshengqile.api.version;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;

import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;

/**
 * 版本管理器*
 * 
 */
public class VersionManager {
    private VersionProperty property; //文件配置
    private static String propertyName = "/version.xml"; //默认的配置文件
    private static VersionManager me = new VersionManager();

    public static VersionManager me() {
        return me;
    }
    
    public VersionManager() {
        this(propertyName);
    }
    
    public VersionManager(String propertyName) {
        try {
            //property = new VersionProperty(VersionManager.class.getResource(propertyName).getPath());
        	property = new VersionProperty(PathKit.getRootClassPath() + propertyName);
        	
        } catch (IOException e) {
            throw new RuntimeException(propertyName + " can not found", e);
        }
    }
    
    /**
     * 检查版本*
     * @param version 版本号
     * @param client 终端类型
     * @return 当前最新版本
     */
    public Version check(String version, String client) {
        if (property == null || StringUtils.isEmpty(version) || StringUtils.isEmpty(client)) {
            return null;
        }

        Version nowVersion = property.getNowVersion(ClientType.getClientType(client));
        if (nowVersion == null) {
			return null;
		}
        
        Integer result = compareVersion(version, nowVersion.getVersion());
        if (result == null || result >= 0) {
			return null;
		}
        
        return nowVersion;
    }
    
    /**
     * 版本号比较   
     * version > nowVersion 返回正值,
     * version < nowVersion 返回负值,
     * version = nowVersion 返回0,
     * version或nowVersion为空 返回null
     * @author yangzhicong
     * @param version 版本号1
     * @param nowVersion 版本号2
     * @return 结果
     */
    public Integer compareVersion(String version, String nowVersion) {
    	if (StrKit.isBlank(version) || StrKit.isBlank(nowVersion)) {
			return null;
		}
    	// 按 "."号进行分割版本号字符串
        String[] versionArray = version.split("\\.");
        String[] nowVersionArray = nowVersion.split("\\.");
        int minLength = Math.min(versionArray.length, nowVersionArray.length);
        int index = 0;
        int diff = 0;
        
		while (index < minLength
				&& (diff = versionArray[index].length() - nowVersionArray[index].length()) == 0
				&& (diff = versionArray[index].compareTo(nowVersionArray[index])) == 0) {
			++index;
		}
		
        //如果已经分出大小, 则直接返回diff, 如果未分出大小, 则再比较位数, 有子版本的为大
        diff = (diff != 0) ? diff : versionArray.length - nowVersionArray.length;
        return diff;
    }
}
